<?php

declare(strict_types=1);
namespace App\Service\CommodityService;

use App\Service\AppService\SystemCacheConfigService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Model\CommodityModel\SupplierCompany;
use Hyperf\DbConnection\Db;
use App\Model\HmCommodityModel\HmSupplierCompany;
use App\Model\HmCommodityModel\HmSupplierCommodity;

/**
 * 韩免供应商拉取商品
 * @author chenshubo
 */
class SupplierCommodityKoreaPullLogService extends BaseService
{
    const TIME_WAIT = 240; //分钟
    const PULL_USER_COUNT = 10; //每次同时拉取供应商的数量
    protected $web_site_url;
    
    
    /**
     * 开启计划任务
     */
    public function runTask($company_code = '')
    {
        $config = SystemCacheConfigService::instance()->getCacheInfoBySystemCode('channel_task_user_limit');
        if (empty($config)) {
            return Normal::returnCode(Normal::FAIL, '参数未配置');
        }
        
        $res = SupplierCommodityPullLogService::instance()->getWaitPullSupplierWareHouseInfoBySupplierCode($company_code);
        if ($res['code'] != Normal::SUC or empty($res["data"])) {
            return $res;
        }
        
        //获取供应商参数
        $supplier               = $res['data'];
        $apiBody                = $supplier['JsonBody'];
        $SupplierID             = $supplier['SupplierID'];
        $CommodityGetStartTime  = microtime(true);
        $CommodityGetTotal      = 0;
        $hmSupplierCompany = HmSupplierCompany::instance()->getSupplierListBySupplierCode($company_code);
        if(empty($hmSupplierCompany)){
            return Normal::returnCode(Normal::FAIL, "没有查到韩国本地数据库的供应商信息");
        }
        
        $hmCompanyId            = $hmSupplierCompany["ID"];
        $limit                  = isset($apiBody["limit"]) ? $apiBody["limit"] : 50;
        $lastPageId             = 0;
        $maxSupplierCommodityId = 0;
        
        //所有供应商拉取完成间隔时间
        $SupplierPullWaitTime = self::TIME_WAIT;
        $CommodityGetNetPeriod = date("Y-m-d H:i:s", time() + $SupplierPullWaitTime * 60);
        
        //初始化拉取状态
        $updateArr = [
            'CommodityGetTotal'         => 0,
            'CommodityGetTaskStatus'    => 0,
            'CommodityGetFinishCount'   => 0,
            'CommodityGetFinishUseTime' => 0.000,
        ];
        SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
        
        //查询出当前供应商商品最大id
        /* $maxHmSupplierCommodity = HmSupplierCommodity::instance()->getMaxHmSupplierCommodityBySupplierCompanyID($hmCompanyId);
         if($maxHmSupplierCommodity){
         $maxSupplierCommodityId = $maxHmSupplierCommodity["max_id"];
         } */
        
        $page = 1;
        while (true)
        {
            //默认每次查询正序50条
            $hmSupplierCommodityList = HmSupplierCommodity::instance()
            ->getCommodityListBySupplierCompanyID($hmCompanyId,$lastPageId,$limit,$maxSupplierCommodityId);
            if (empty($hmSupplierCommodityList))
            {
                //是否最后一页
                $MessageBody  = [
                    'SupplierID'        => $SupplierID,
                    'SupplierCode'      => $company_code,
                    'IsFirstPage'       => $page == 1 ? 1 : 0,
                    'DataPage'          => $page,
                    'IsLastPage'        => 1,
                    'GoodsItemList'     => $result_goods_list
                ];
                SupplierCommodityPullLogService::instance()->publish($MessageBody);
                break;
            }
        
            //获取当前查询结果中的最后一条商品信息
            $endCommodity       = end($hmSupplierCommodityList);
            $lastPageId         = $endCommodity["ID"];
        
            //开始查询处理每一页商品
            $result_goods_list  = HmCommodityGoodsService::instance()->queryPageGoodsList($hmCompanyId,$hmSupplierCommodityList);
            if( empty($result_goods_list) )
            {
                echo "当前无数据需要处理".PHP_EOL;
                $page ++;
                continue;
            }
        
            //开始同步到MQ队列
            $pull_count         = count($result_goods_list);
            $CommodityGetTotal += $pull_count;
        
            $updateArr = [
                'CommodityGetTaskStatus'    => 1,
                'CommodityGetFinishCount'   => Db::raw('CommodityGetFinishCount + ' . $pull_count)
            ];
        
            SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
        
            //开始分批发送
            $chunk_batch_list = array_chunk($result_goods_list,50);
            foreach ($chunk_batch_list as $batchList)
            {
                $MessageBody  = [
                    'SupplierID'        => $SupplierID,
                    'SupplierCode'      => $company_code,
                    'IsFirstPage'       => $page == 1 ? 1 : 0,
                    'DataPage'          => $page,
                    'IsLastPage'        => 0,
                    'GoodsItemList'     => $batchList
                ];
                SupplierCommodityPullLogService::instance()->publish($MessageBody);
            }
            $page++;
        }
        
        //拉取完成
        $updateArr = [
            'CommodityGetTotal'         => $CommodityGetTotal,
            'CommodityGetTaskStatus'    => 2,
            'CommodityGetContents'      => '拉取完成',
            'CommodityGetFinishUseTime' => bcsub((string)microtime(true),(string)$CommodityGetStartTime, 3),
            'CommodityGetNetPeriod'     => $CommodityGetNetPeriod
        ];
        SupplierCompany::instance()->where('ID', $SupplierID)->update($updateArr);
        return Normal::returnCode(Normal::SUC, '拉取完成');
    }
}
